package com.itheima.app.interceptor;


import cn.hutool.core.util.StrUtil;
import com.itheima.app.manager.UserManager;
import com.itheima.domain.db.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//在拦截器中进行token的校验和处理
@Component
public class TokenInterceptor implements HandlerInterceptor {
  @Autowired
  private UserManager userManager;
    //预处理
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
     //获取token
        String token = request.getHeader("Authorization");

        //判断是否为空
        if (StrUtil.isEmpty(token)){
            response.setStatus(401);  //拦截
            return false;
        }
        //2.解析token
        User user = userManager.findUserByToken(token);
        if (user==null){
            response.setStatus(401);//拦截
            return false;
        }
        //3.将user存储到线程中
        UserHolder.set(user);
        //4.放行
        return true;
    }
  //最终处理
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        UserHolder.remove();
    }
}
